﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;

namespace RouterControlTest
{
    /// <summary>
    /// Summary description for LocalDb
    /// </summary>
    [TestClass]
    public class LocalDb
    {
        public LocalDb()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test 
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        private RouterControl.LocalDb.LocalDbConnector _conn;

        [TestInitialize]
        public void Initialize()
        {
            var target = new FileInfo("LocalDbTest.sqlite");
            var source = new FileInfo(@"..\..\..\RouterControl.LocalDb\RouterControlLocalDb.sqlite");

            File.Copy(
                source.FullName,
                target.FullName,
                true
                );

            _conn = new RouterControl.LocalDb.LocalDbConnector(target);
        }

        private RouterControl.LocalDb.LocalDbConnector.DeviceInfo RegisterDevice()
        {
            return _conn.RegisterDevice(
                Guid.NewGuid().ToString(),
                "TestType"
                );
        }

        [TestMethod]
        public void WriteAndReadTraffic()
        {
            var dev = RegisterDevice();

            // generate random traffic
            var rnd = new Random(DateTime.Now.Millisecond);
            var count = rnd.Next(20, 50);
            var splitIndex = rnd.Next(0, count);
            var dt = DateTime.Now;
            DateTime splitTime = DateTime.MinValue;

            for (int i = 0; i < count; i++)
            {
                _conn.AddTrafficInfo(dev, new RouterControl.LocalDb.LocalDbConnector.TrafficInfo()
                    {
                        TimeStamp = dt.AddSeconds(i * 5),
                        UpBytesPerSecond = rnd.Next(0, (1024 * 1024) / 8), // 1 MBit
                        DownBytesPerSecond = rnd.Next(0, (6 * 1024 * 1024) / 8), // 6 MBit
                    });

                // split?
                if (splitIndex == i)
                    splitTime = dt.AddSeconds(i * 5);
            }

            // query traffic
            {
                var tt = _conn.GetTrafficInfo(dev, -1);

                foreach (var t in tt)
                {
                    Console.WriteLine(
                        "{0}: U:{1} / D:{2}",
                        t.TimeStamp,
                        t.UpBytesPerSecond,
                        t.DownBytesPerSecond
                        );
                }

                Assert.AreEqual<int>(count, tt.Count, "retrieved traffic info count does not match written one");
            }

            // query traffic since
            {
                var tt = _conn.GetTrafficInfoSince(dev, splitTime, -1);

                /*foreach (var t in tt)
                {
                    Console.WriteLine(
                        "{0}: U:{1} / D:{2}",
                        t.TimeStamp,
                        t.UpBytesPerSecond,
                        t.DownBytesPerSecond
                        );
                }*/

                Assert.AreEqual<int>(count - splitIndex - 1, tt.Count, "retrieved traffic info since count does not match written one after split");
            }
        }

        [TestMethod]
        public void UnusedPages()
        {
            var dev = RegisterDevice();

            // generate random traffic
            var rnd = new Random(DateTime.Now.Millisecond);
            var count = rnd.Next(200, 300);
            var dt = DateTime.Now;

            for (int i = 0; i < count; i++)
            {
                _conn.AddTrafficInfo(dev, new RouterControl.LocalDb.LocalDbConnector.TrafficInfo()
                {
                    TimeStamp = dt.AddSeconds(i * 5),
                    UpBytesPerSecond = rnd.Next(0, (1024 * 1024) / 8), // 1 MBit
                    DownBytesPerSecond = rnd.Next(0, (6 * 1024 * 1024) / 8), // 6 MBit
                });
            }

            // dump
            Console.WriteLine("{0:P}", _conn.GetUnusedPagesPercentage());

            // delete device
            _conn.DeleteDevice(dev);

            // dump
            Console.WriteLine("{0:P}", _conn.GetUnusedPagesPercentage());

            // maintain
            _conn.MaintainDatabase();

            // dump
            Console.WriteLine("{0:P}", _conn.GetUnusedPagesPercentage());
        }

        [TestMethod]
        public void HasTable()
        {
            Assert.IsTrue(_conn.HasObject("Devices"));
            Assert.IsFalse(_conn.HasObject("DoesNotExist-1234"));
        }
    }
}
